import express from "express";
import fs from "node:fs";
import path from "path";
import user from "../services/user/index.js";

const __dirname = path.join(process.cwd(), "src/router");
const routers = fs.readdirSync(__dirname);
const router = express.Router();

// 登录校验中间件
router.use("/", user.loginCheck.bind(user));

// 动态挂载路由模块
async function loadRoutes() {
  for (let r of routers) {
    try {
      let filename = path.basename(r, ".js");
      if (filename === "index") continue;
      let routeModule = (await import(`./${r}`)).default;
      router.use(`/${filename}`, routeModule);
    } catch (error) {
      console.error(`加载 ${r} 路由失败:`, error);
    }
  }
}

loadRoutes().then(() => {
  console.log("路由加载完成");
});

export default router;
